//! Common class definition

#include <QSettings>

#include "include/Common.h"
#include <assert.h>
#include <sstream>
#include <cstdlib>
#include <string>
#include <iostream>
#include <stdio.h>

#include <QDir>
#include <QFileInfo>

#ifdef _WIN32
#include <windows.h>
#include <Lmcons.h>
#endif

using namespace std;

//bool Settings::m_requestLeaf = false;
TreeItem* Settings::m_buffer = 0;

string intToString(int i)
{
	std::stringstream out;
	out << i;
	return out.str();
}

string floatToString(float f)
{
	std::stringstream out;
	out << f;
	return out.str();
}

void Tokenize(const string& str,
			  vector<string>& tokens,
			  const string& delimiters = " ")
{
	// Skip delimiters at beginning.
	string::size_type lastPos = str.find_first_not_of(delimiters, 0);
	// Find first "non-delimiter".
	string::size_type pos     = str.find_first_of(delimiters, lastPos);

	while (string::npos != pos || string::npos != lastPos)
	{
		// Found a token, add it to the vector.
		tokens.push_back(str.substr(lastPos, pos - lastPos));
		// Skip delimiters.  Note the "not_of"
		lastPos = str.find_first_not_of(delimiters, pos);
		// Find next "non-delimiter"
		pos = str.find_first_of(delimiters, lastPos);
	}
}

QString getHome()
{
#ifdef _WIN32
	QSettings settings(QSettings::UserScope, "Microsoft", "Windows");
	settings.beginGroup("CurrentVersion/Explorer/Shell Folders");
	QString personal = settings.value("Personal").toString();
#else
	QString personal = getenv("HOME");
#endif
	return personal;
}

QString getTFCUserDir()
{
	QString personal = getHome();

	personal += "/turboflashcards";

	if (!QDir(personal).exists())
		QDir().mkdir(personal);

	return personal;
}

QString getTFCMediaDir(QString deckpath)
{
	QString path = QFileInfo(deckpath).path();
	path += "/";
	path += QFileInfo(deckpath).baseName();
	path += "_media";
	if (!QDir(path).exists())
		QDir().mkdir(path);
	return path;
}

QString getTFCGeneratedAudioDir(QString depthpath)
{
	QString personal = getTFCMediaDir(depthpath);
	personal += "/generated_audio";
	if (!QDir(personal).exists())
		QDir().mkdir(personal);
	return personal;
}

QString getUserName()
{
	QString userName("");
#if defined(__unix__) or defined(__APPLE_CC__)
	userName = getenv("USER");
#elif defined(_WIN32)
	TCHAR name [ UNLEN + 1 ];
	DWORD size = UNLEN + 1;

	GetUserName( (TCHAR*)name, &size );

#ifdef UNICODE
	userName = QString::fromUtf16((ushort*)name);
#else
	userName = QString::fromLocal8Bit(name);
#endif

#endif
	return userName;
}

void QThreadEx::run()
{
	exec();
}

#if defined(__unix__) or defined(__APPLE_CC__)
#define POPEN popen
#define PCLOSE pclose
#elif defined(_WIN32)
#define POPEN _popen
#define PCLOSE _pclose
#endif

QString sysExec(const char* cmd) {
		FILE* pipe = POPEN(cmd, "r");
		if (!pipe) return "ERROR";
		char buffer[128];
		QString result = "";
		while(!feof(pipe)) {
				if(fgets(buffer, 128, pipe) != NULL)
						result += buffer;
		}
		PCLOSE(pipe);
		return result;
}
